package service

import (
	"gorm.io/gorm"
	"guns-go/global"
	"guns-go/model"
	"guns-go/model/request"
	"strconv"
)

func GetUserRoleIdList(userId int) (err error, ids []int) {

	var userRoles []model.SysUserRole
	err = global.GVA_DB.Where("user_id = ?", userId).Find(&userRoles).Error

	if err != nil {
		return err, nil
	}

	roleIds := make([]int, 0)
	if len(userRoles) > 0 {
		for _, sysUserRole := range userRoles {
			roleIds = append(roleIds, sysUserRole.RoleId)
		}
	}

	return err, roleIds
}

func DeleteUserRoleByIds(ids []int, tx *gorm.DB) error {
	return tx.Delete(model.SysUserRole{}, "id in (?)", ids).Error
}

func DeleteUserRoleByUserId(userId int, tx *gorm.DB) error {
	return tx.Delete(model.SysUserRole{}, "user_id = ?", userId).Error
}

func DeleteUserRoleListByRoleId(roleId int, tx *gorm.DB) error {
	return tx.Delete(model.SysUserRole{}, "role_id = ?", roleId).Error
}

func GetUserRoleDataScopeIdList(userId int, orgId int) (err error, scopes []int) {

	err, roleIds := GetUserRoleIdList(userId)

	if err != nil {
		return err, nil
	}

	if len(roleIds) > 0 {
		err, ids := GetUserDataScopeIdList(roleIds, orgId)

		if err != nil {
			return err, nil
		}
		return err, ids
	}
	return err, make([]int, 0)
}

func DeleteUserRoleListByUserId(userId int, tx *gorm.DB) error {

	err := tx.Delete(model.SysUserRole{}, "user_id = ?", userId).Error
	return err
}

func SaveUserRole(userRole *model.SysUserRole, tx *gorm.DB) error {

	err := tx.Create(userRole).Error
	return err
}

func SysUserGrantRole(sysUserParam *request.SysUserParam) error {

	userId := sysUserParam.Id

	tx := global.GVA_DB.Begin()

	err := DeleteUserRoleByUserId(userId, tx)

	if err != nil {
		tx.Rollback()
		return err
	}

	//授权角色
	for _, roleId := range sysUserParam.GrantRoleIdList {

		userRole := new(model.SysUserRole)

		userRole.UserId = userId
		roleInt, _ := strconv.Atoi(roleId)
		userRole.RoleId = roleInt

		err = SaveUserRole(userRole, tx)

		if err != nil {
			tx.Rollback()
			return err
		}
	}
	tx.Commit()
	return nil
}
